package com.ks.service;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CreateCache;
import com.ks.dao.UserDao;
import com.ks.model.User;
import com.ks.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    public UserDao userDao;

//缓存，2分钟过期
    @CreateCache(name = "UserService.userCache", expire = 120
            , cacheType = CacheType.BOTH, localLimit = 50)
    private Cache<Long, User> userCache;

    /**获取user*/
    public User getUser(Long id){
        System.out.println("--------查询，1.进入user-------id-"+id);
        User user = userCache.get(id);
        System.out.println("--------查询，2。缓存查询user-------user-"+ StringUtils.toStr( user));
        if(user==null){
            Optional<User> opt = userDao.findById(id);
            System.out.println("--------查询，3。sql查询user-------opt-"+StringUtils.toStr( opt));
            if(opt.isPresent()) {
                user = userDao.findById(id).get();
                userCache.put(id, user);
                System.out.println("--------查询，4。设置缓存user,-------user-"+StringUtils.toStr( user));
            }
        }
        System.out.println("--------查询，5。返回user-------user-"+StringUtils.toStr( user));
        return user ;
    }
    /**删除user*/
    public boolean deleteCache(Long id){
        System.out.println("=====清缓存,1=======id="+id);
        boolean b = userCache.remove(id);
        System.out.println("=====清缓存,1=======结果="+b);
        return b;
    }


    //2分钟内，只会调用一次
    @Cached(name="UserService.list", expire = 120)
    public List<User> list(){
        System.out.println("111111");
        List<User> all = userDao.findAll();
        System.out.println("11111122222");
        return all;
    }
}
